/**
 * 
 */
package com.android.zing.dialog;

import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.zing.R;
import com.android.zing.ZME_Base;
import com.android.zing.ZME_DialogListener;
import com.android.zing.ZME_Error;
import com.android.zing.ZME_Utils;

/**
 * @author trangdoan
 * 
 */
public class ZME_Dialog extends Dialog {
	static final int FB_BLUE = 0xFF6D84B4;
	static final float[] DIMENSIONS_DIFF_LANDSCAPE = { 20, 60 };
	static final float[] DIMENSIONS_DIFF_PORTRAIT = { 40, 60 };
	static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
			ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
	static final int MARGIN = 4;
	static final int PADDING = 2;
	static final String DISPLAY_STRING = "touch";
	static final String FB_ICON = "icon.png";

	public static final String TAG = "ZME_Dialog";

	private String mUrl;
	private ZME_DialogListener mListener;
	private ProgressDialog mSpinner;
	private WebView mWebView;
	private LinearLayout mContent;
	private TextView mTitle;

	private String DEBUG = "";

	public ZME_Dialog(Context context, String url, ZME_DialogListener listener) {
		super(context);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mUrl = url;
		mListener = listener;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSpinner = new ProgressDialog(getContext());
		mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mSpinner.setMessage("Loading...");

		mContent = new LinearLayout(getContext());
		mContent.setOrientation(LinearLayout.VERTICAL);
		//setUpTitle();
		setUpWebView();
		Display display = getWindow().getWindowManager().getDefaultDisplay();
		final float scale = getContext().getResources().getDisplayMetrics().density;
		int orientation = getContext().getResources().getConfiguration().orientation;
		float[] dimensions = (orientation == Configuration.ORIENTATION_LANDSCAPE) ? DIMENSIONS_DIFF_LANDSCAPE
				: DIMENSIONS_DIFF_PORTRAIT;
		addContentView(
				mContent,
				new LinearLayout.LayoutParams(display.getWidth()
						- ((int) (dimensions[0] * scale + 0.5f)), display
						.getHeight() - ((int) (dimensions[1] * scale + 0.5f))));
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void setUpWebView() {
		mWebView = new WebView(getContext());
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.setWebViewClient(new ZME_Dialog.FbWebViewClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		Log.d(TAG, "start load web view with URL: " + mUrl);
		mWebView.loadUrl(mUrl);
		mWebView.setLayoutParams(FILL);
		mContent.addView(mWebView);
		Log.d(TAG, "end load web view with URL: " + mUrl);
	}

	private class FbWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d(TAG, "shouldOverrideUrlLoading " + url);
			if (url.startsWith(ZME_Base.REDIRECT_URI.toLowerCase())) {
				Bundle values = ZME_Utils.parseUrl(url);
				Log.d(TAG, "after parse URL : " + values.toString());

				String error = values.getString("error");
				String authCode = values.getString("code");
				values.putString("DEBUG", DEBUG);
				if (authCode != null) {
					mListener.onComplete(values);
				} else {
					mListener.onZmeError(new ZME_Error(error));
				}

				ZME_Dialog.this.dismiss();
				return true;
			} else if (url.startsWith(ZME_Base.CANCEL_URI)) {
				mListener.onCancel();
				ZME_Dialog.this.dismiss();
				return true;
			} else if (url.contains(DISPLAY_STRING)) {
				return false;
			}
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Log.d(TAG, "onReceivedError with errorCode: " + errorCode);
			Log.d(TAG, "onReceivedError with error description: " + description);
			super.onReceivedError(view, errorCode, description, failingUrl);
			mListener.onError(new ZME_DialogError(description, errorCode,
					failingUrl));
			ZME_Dialog.this.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d(TAG, "Webview loading URL: " + url);
			DEBUG += TAG + " web view starts to load " + url + "at "
					+ new Date() + " \n";
			super.onPageStarted(view, url, favicon);
			mSpinner.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			Log.d(TAG, "Webview finished URL: " + url);
			DEBUG += TAG + "web view finished loading " + url + "at "
					+ new Date() + " \n";
			super.onPageFinished(view, url);
			//String title = mWebView.getTitle();
//			if (title != null && title.length() > 0) {
//				mTitle.setText(title);
//			}
			mSpinner.dismiss();
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			handler.proceed();
		}
	}
}
